import Vue from 'vue'
import VueRouter from 'vue-router'
import login from '@/views/login'
import layout from '@/views/layout'
import shouye from '@/views/shouye'
import my from '@/views/my'
import news from '@/views/news'
import search from '@/views/search'
import collect from '@/views/collect'
import rent from '@/views/rent'
import { getToken } from '@/utils/storage'
import gorent from '@/views/gorent'
import listcities from '@/views/listcities'
import maphouse from '@/views/maphouse'

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    {
      path: '/',
      component: layout,
      children: [
        {
          path: '/shouye',
          component: shouye
        },
        {
          path: '/search',
          component: search
        },
        {
          path: '/news',
          component: news
        },
        {
          path: '/my',
          component: my
        }
      ]
    },
    {
      path: '/login',
      component: login
    },
    {
      path: '/collect',
      component: collect
    },
    {
      path: '/rent',
      component: rent
    },
    {
      path: '/gorent',
      component: gorent
    },
    {
      path: '/listcities',
      component: listcities
    },
    {
      path: '/maphouse',
      component: maphouse
    }

  ]
})

// 全局守卫
const whiteList = ['/login', '/shouye', '/search', '/news', '/my'] // 白名单列表，记录无需权限访问的所有页面
router.beforeEach((to, from, next) => {
  // to 去哪里, from从哪里来,next是一个函数
  // 只有调用next，才会正常放行,next(path)，可以跳到指定路径
  const token = getToken()
  // 如果有token 直接放行i
  if (token) {
    next()
  } else {
    // 如果没有 token，就检测是否去的是白名单的页面，如果是，直接放行
    if (whiteList.includes(to.path)) {
      next()
    } else {
      // (2) 否则拦截到登录
      next('/login')
    }
  }
  next()
})

export default router
